<?php

namespace app\common\model;

use think\Model;


class Goods extends Model
{
    # 商品分类
    public function goodsCate(){
        return $this->belongsTo("category","cate_id","id")->bind("cate_name");
    }
    # 商品分类全部数据
    public function category(){
        return $this->belongsTo("category","cate_id","id");
    }
    # 商品类型 type表关联
    public function goodsType(){
        return $this->belongsTo("type","type_id","id")->bind("type_name");
    }
    # 关联商品类型 type表的全部数据
    public function type(){
        return $this->belongsTo("type","type_id","id");
    }
    # 品牌表关联 brand 
    public function goodsBrand(){
        return $this->belongsTo("brand","brand_id","id")->bind("name");
    }
    # 品牌关联 获取全部的数据 brand 
    public function brand(){
        return $this->belongsTo("brand","brand_id","id");
    }
    # 商品图片 goods_images 表
    public function goodsImage(){
        return $this->hasMany("goods_images","goods_id","id");
    }
    # 商品规格 spec_goods 表
    public function goodsSpec(){
        return $this->hasMany("spec_goods","goods_id","id");
    }
    public function getGoodsAttrAttr($value)
    {
        return $value ? json_decode($value,true):[];
    }
    protected static function init()
    {
        //实例化ES工具类
        $es = new \tools\es\MyElasticsearch();
        //设置新增回调
        self::afterInsert(function($goods)use($es){
            //添加文档
            $doc = $goods->visible(['id', 'goods_name', 'goods_desc', 'goods_price'])->toArray();
            $doc['cate_name'] = $goods->category->cate_name;
            $es->add_doc($goods->id, $doc, 'goods_index', 'goods_type');
        });
        //设置更新回调
        self::afterUpdate(function($goods)use($es){
            //修改文档
            $doc = $goods->visible(['id', 'goods_name', 'goods_desc', 'goods_price', 'cate_name'])->toArray();
            $doc['cate_name'] = $goods->category->cate_name;
            $body = ['doc' => $doc];
            $es->update_doc($goods->id, 'goods_index', 'goods_type', $body);
        });
        //设置删除回调
        self::afterDelete(function($goods)use($es){
            //删除文档
            $es->delete_doc($goods->id, 'goods_index', 'goods_type');
        });
    }
}
